package com.anolesoft.yr.mbus.base.service.impl;

import com.anolesoft.yr.exception.ServiceException;
import com.anolesoft.yr.mbus.base.dto.BaseCompanyDTO;
import com.anolesoft.yr.mbus.base.entity.BaseCompanyDO;
import com.anolesoft.yr.mbus.base.mapper.BaseCompanyMapper;
import com.anolesoft.yr.mbus.base.service.BaseCompanyService;
import com.anolesoft.yr.util.CommonUtils;
import com.anolesoft.yr.util.CustomBeanUtils;
import com.anolesoft.yr.util.PageData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhj
 * @date 2020/8/9 9:52
 */
@Service("baseCompanyServiceImpl")
public class BaseCompanyServiceImpl implements BaseCompanyService {
    @Autowired
    private BaseCompanyMapper baseCompanyMapper;

    private void checkUnique(BaseCompanyDTO baseCompanyDTO, boolean isModify) {
        String objuid = baseCompanyDTO.getObjuid();
        String companyCode = baseCompanyDTO.getCompanyCode();
        String companyName = baseCompanyDTO.getCompanyName();
        if (isModify) {
            if (baseCompanyMapper.checkUniqueForCompanyCodeUpdate(companyCode, objuid) > 0) {
                throw new ServiceException("公司编号已存在");
            }
            if (baseCompanyMapper.checkUniqueForCompanyNameUpdate(companyName, objuid) > 0) {
                throw new ServiceException("公司全称已存在");
            }
        } else {
            if (baseCompanyMapper.checkUniqueForCompanyCode(companyCode) > 0) {
                throw new ServiceException("公司编号已存在");
            }
            if (baseCompanyMapper.checkUniqueForCompanyName(companyName) > 0) {
                throw new ServiceException("公司全称已存在");
            }
        }
    }

    @Transactional
    @Override
    public int create(BaseCompanyDTO baseCompanyDTO) {
        checkUnique(baseCompanyDTO, false);
        return baseCompanyMapper.insert(BaseCompanyDO.builder()
                .companyAddress(baseCompanyDTO.getCompanyAddress())
                .companyOtherName(baseCompanyDTO.getCompanyOtherName())
                .companyName(baseCompanyDTO.getCompanyName())
                .companyCode(baseCompanyDTO.getCompanyCode())
                .baseRegionUid(baseCompanyDTO.getBaseRegionUid())
                .factoryCode(baseCompanyDTO.getFactoryCode())
                .modifyUserUid(baseCompanyDTO.getModifyUserUid())
                .taxNumber(baseCompanyDTO.getTaxNumber())
                .remark(baseCompanyDTO.getRemark())
                .objuid(baseCompanyDTO.getObjuid())
                .legalPerson(baseCompanyDTO.getLegalPerson())
                .faxNumber(baseCompanyDTO.getFaxNumber())
                .establishTime(baseCompanyDTO.getEstablishTime())
                .email(baseCompanyDTO.getEmail())
                .createUserUid(baseCompanyDTO.getCreateUserUid())
                .contactPerson(baseCompanyDTO.getContactPerson())
                .contactNumber(baseCompanyDTO.getContactNumber())
                .companyWebsite(baseCompanyDTO.getCompanyWebsite())
                .companyType(baseCompanyDTO.getCompanyType())
                .companyGrade(baseCompanyDTO.getCompanyGrade())
                .bank(baseCompanyDTO.getBank())
                .account(baseCompanyDTO.getAccount())
                .build());
    }

    @Transactional
    @Override
    public int modify(BaseCompanyDTO baseCompanyDTO) {
        checkUnique(baseCompanyDTO, true);
        BaseCompanyDO baseCompanyDO = baseCompanyMapper.selectOneById(baseCompanyDTO.getObjuid());
        if (baseCompanyDO == null) {
            baseCompanyDO = BaseCompanyDO.builder().build();
        }
        baseCompanyDO.setCompanyAddress(baseCompanyDTO.getCompanyAddress());
        baseCompanyDO.setCompanyOtherName(baseCompanyDTO.getCompanyOtherName());
        baseCompanyDO.setCompanyName(baseCompanyDTO.getCompanyName());
        baseCompanyDO.setCompanyCode(baseCompanyDTO.getCompanyCode());
        baseCompanyDO.setBaseRegionUid(baseCompanyDTO.getBaseRegionUid());
        baseCompanyDO.setFactoryCode(baseCompanyDTO.getFactoryCode());
        baseCompanyDO.setModifyUserUid(baseCompanyDTO.getModifyUserUid());
        baseCompanyDO.setTaxNumber(baseCompanyDTO.getTaxNumber());
        baseCompanyDO.setRemark(baseCompanyDTO.getRemark());
        baseCompanyDO.setLegalPerson(baseCompanyDTO.getLegalPerson());
        baseCompanyDO.setFaxNumber(baseCompanyDTO.getFaxNumber());
        baseCompanyDO.setEstablishTime(baseCompanyDTO.getEstablishTime());
        baseCompanyDO.setEmail(baseCompanyDTO.getEmail());
        baseCompanyDO.setContactPerson(baseCompanyDTO.getContactPerson());
        baseCompanyDO.setContactNumber(baseCompanyDTO.getContactNumber());
        baseCompanyDO.setCompanyWebsite(baseCompanyDTO.getCompanyWebsite());
        baseCompanyDO.setCompanyType(baseCompanyDTO.getCompanyType());
        baseCompanyDO.setCompanyGrade(baseCompanyDTO.getCompanyGrade());
        baseCompanyDO.setBank(baseCompanyDTO.getBank());
        baseCompanyDO.setAccount(baseCompanyDTO.getAccount());

        return baseCompanyMapper.update(baseCompanyDO);
    }

    @Transactional
    @Override
    public int remove(String id) {
        return baseCompanyMapper.delete(id);
    }

    @Transactional
    @Override
    public int removeBatch(List<String> ids) {
        int res = 0;
        for (String id : ids) {
            res += baseCompanyMapper.delete(id);
        }
        return res;
    }

    @Override
    public List<BaseCompanyDTO> selectAll() {
        return baseCompanyMapper.selectAll().stream().map(t -> CustomBeanUtils.baseCompanyDO2DTO(t)).collect(Collectors.toList());
    }

//    private BaseCompanyDTO do2dto(BaseCompanyDO t) {
//        BaseRegionDO region = t.getRegion();
//        BaseRegionDTO baseRegionDTO = null;
//        if (region != null) {
//            baseRegionDTO = BaseRegionDTO.builder()
//                    .remark(region.getRemark())
//                    .parentUid(StringUtils.isEmpty(region.getParentUid()) ? "-" : region.getParentUid())
//                    .modifyUserUid(region.getModifyUserUid())
//                    .deleteFlag(region.getDeleteFlag())
//                    .createUserUid(region.getCreateUserUid())
//                    .regionCode(region.getRegionCode())
//                    .regionLevel(region.getRegionLevel())
//                    .regionName(region.getRegionName())
//                    .factoryCode(region.getFactoryCode())
//                    .objuid(region.getObjuid())
//                    .build();
//        } else {
//            baseRegionDTO = new BaseRegionDTO();
//        }
//
//        List<BaseContactDTO> baseContactDOTS = t.getContacts().stream().map(baseContactDTO -> BaseContactDTO.builder()
//                .contactNumber(baseContactDTO.getContactNumber())
//                .contactPerson(baseContactDTO.getContactPerson())
//                .createTime(baseContactDTO.getCreateTime())
//                .createUserUid(baseContactDTO.getCreateUserUid())
//                .crmAddress(baseContactDTO.getCrmAddress())
//                .deleteFlag(baseContactDTO.getDeleteFlag())
//                .factoryCode(baseContactDTO.getFactoryCode())
//                .modifyTime(baseContactDTO.getModifyTime())
//                .modifyUserUid(baseContactDTO.getModifyUserUid())
//                .objuid(baseContactDTO.getObjuid())
//                .postcode(baseContactDTO.getPostcode())
//                .remark(baseContactDTO.getRemark())
//                .targetUid(baseContactDTO.getTargetUid())
//                .type(baseContactDTO.getType())
//                .build()).collect(Collectors.toList());
//
//        return BaseCompanyDTO.builder()
//                .account(t.getAccount())
//                .bank(t.getBank())
//                .baseRegionUid(t.getBaseRegionUid())
//                .companyAddress(t.getCompanyAddress())
//                .companyCode(t.getCompanyCode())
//                .companyGrade(t.getCompanyGrade())
//                .companyName(t.getCompanyName())
//                .companyOtherName(t.getCompanyOtherName())
//                .companyType(t.getCompanyType())
//                .companyWebsite(t.getCompanyWebsite())
//                .contactNumber(t.getContactNumber())
//                .contactPerson(t.getContactPerson())
//                .createTime(t.getCreateTime())
//                .createUserUid(t.getCreateUserUid())
//                .deleteFlag(t.getDeleteFlag())
//                .email(t.getEmail())
//                .establishTime(t.getEstablishTime())
//                .factoryCode(t.getFactoryCode())
//                .faxNumber(t.getFaxNumber())
//                .legalPerson(t.getLegalPerson())
//                .modifyTime(t.getModifyTime())
//                .modifyUserUid(t.getModifyUserUid())
//                .objuid(t.getObjuid())
//                .region(baseRegionDTO)
//                .remark(t.getRemark())
//                .taxNumber(t.getTaxNumber())
//                .contacts(baseContactDOTS)
//                .build();
//    }

    @Override
    public PageData<List<BaseCompanyDTO>> selectAll(Integer limit, Integer curr) {
        Page<BaseCompanyDO> page = new Page<>(curr, limit);
        long total = page.getTotal();
        //return baseCompanyMapper.selectAll(page).stream().map(t -> do2dto(t)).collect(Collectors.toList());
        List<BaseCompanyDTO> baseCompanyDTOS = baseCompanyMapper.selectPageAll(page).stream().map(t -> CustomBeanUtils.baseCompanyDO2DTO(t)).collect(Collectors.toList());
        return new PageData<>((int) page.getTotal(), baseCompanyDTOS);
    }

    @Override
    public Optional<BaseCompanyDTO> selectOneById(String id) {
        BaseCompanyDO baseCompanyDO = baseCompanyMapper.selectOneById(id);
        if (baseCompanyDO != null) {
            return Optional.of(CustomBeanUtils.baseCompanyDO2DTO(baseCompanyDO));
        }
        return Optional.empty();
    }

    @Override
    public List<BaseCompanyDTO> selectList(BaseCompanyDTO baseCompanyDTO) {
        BaseCompanyDO companyDO = buildCondition(baseCompanyDTO);
        return baseCompanyMapper.selectList(companyDO).stream().map(t -> CustomBeanUtils.baseCompanyDO2DTO(t)).collect(Collectors.toList());
    }

    @Override
    public PageData<List<BaseCompanyDTO>> selectList(BaseCompanyDTO baseCompanyDTO, Integer limit, Integer curr) {
        BaseCompanyDO companyDO = buildCondition(baseCompanyDTO);
        //return baseCompanyMapper.selectList(companyDO, new Page<>(curr, limit)).stream().map(t -> do2dto(t)).collect(Collectors.toList());
        Page<BaseCompanyDO> page = new Page<>(curr, limit);
        List<BaseCompanyDTO> baseCompanyDTOS = baseCompanyMapper.selectPageList(companyDO, page).stream().map(t -> CustomBeanUtils.baseCompanyDO2DTO(t)).collect(Collectors.toList());
        return new PageData<>((int) page.getTotal(), baseCompanyDTOS);
    }

    private BaseCompanyDO buildCondition(BaseCompanyDTO baseCompanyDTO) {
        return BaseCompanyDO.builder()
                .factoryCode(CommonUtils.stringNull(baseCompanyDTO.getFactoryCode()))
                .baseRegionUid(CommonUtils.stringNull(baseCompanyDTO.getBaseRegionUid()))
                .companyCode(CommonUtils.warpStringNull(baseCompanyDTO.getCompanyCode()))
                .companyName(CommonUtils.warpStringNull(baseCompanyDTO.getCompanyName()))
                .companyOtherName(CommonUtils.warpStringNull(baseCompanyDTO.getCompanyOtherName()))
                .companyAddress(CommonUtils.warpStringNull(baseCompanyDTO.getCompanyAddress()))
                .objuid(CommonUtils.stringNull(baseCompanyDTO.getObjuid()))
                .build();
    }
}
